package com.fengchao.util;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http工具类
 * Created by wangnian on 2016/6/2.
 */
public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpget);
            HttpEntity httpEntity = response.getEntity();
            String strResult = EntityUtils.toString(httpEntity);
            logger.info("url:{},response:{}", url, strResult);
            httpClient.close();
            return strResult;
        } catch (Exception ex) {
            logger.warn("excption:{}", ex);
        }
        return null;
    }

    /**
     * post请求
     *
     * @param url
     * @return
     */
    public static String post(String url, Map<String, String> map) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);
            if (map != null) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (String key : map.keySet()) {
                    nvps.add(new BasicNameValuePair(key, map.get(key)));
                }
                httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
            }
            CloseableHttpResponse response = httpClient.execute(httpost);
            String strResult = EntityUtils.toString(response.getEntity());
            logger.info("url:{} ,map:{},response:{}", url, map, strResult);
            httpClient.close();
            return strResult;
        } catch (Exception ex) {
            logger.warn("excption:{}", ex);
        }
        return null;
    }
}
